package pro.softzhang.algo.lc;

import pro.softzhang.algo.common.ListNode;
import pro.softzhang.algo.flag.book.BOfferII;
import pro.softzhang.algo.flag.difficulty.DGreen;
import pro.softzhang.algo.flag.knowledge.KLinkedList;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
 */
@BOfferII(6)
@KLinkedList
@DGreen
public class ReversePrint {
    public static void main(String[] args) {

    }

    /**
     * 使用栈实现
     */
    static
    class Solution {
        public int[] reversePrint(ListNode head) {
            Stack<Integer> stack = new Stack<>();
            while (head != null) {
                stack.push(head.val);
                head = head.next;
            }

            int[] arr = new int[stack.size()];
            for (int i = 0; !stack.isEmpty() ; i++) {
                arr[i] = stack.pop();
            }

            return arr;
        }
    }

    /**
     * 使用双循环实现
     */
    static
    class Solution1 {
        public int[] reversePrint(ListNode head) {
            int length = 0;
            ListNode p = head;
            for (;p != null; p = p.next, length++) {}

            int[] arr = new int[length];
            for (int i = length; head != null; i--, head = head.next)
                arr[i - 1] = head.val;
            return arr;
        }
    }
}
